package cn.cvs.controller;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;
import cn.cvs.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    @Qualifier("sysUserServiceImpl")
    private SysUserService sysUserService;
    //登录
    @RequestMapping("login")
    public String login(Model model, HttpServletRequest request, HttpSession session,
                           String account, String password){
        //调用service方法进行用户匹配
        SysUser sysUser = sysUserService.login(account, password);
        if (sysUser ==null){

            model.addAttribute("error","用户名或密码不正确");
            return "login";
        }
        request.getSession().setAttribute("userSession",sysUser);

        return "redirect:/frame";
    }

    @RequestMapping("list")
    public String getUserList(Model model, String realName,Integer roleId,@RequestParam(defaultValue = "1") Integer pageIndex){
        Integer pageSize= 7 ;
        //总记录数（表）
        int totalCount = sysUserService.count(realName);

        int totalPageCount = totalCount/pageSize;

        if (totalCount%pageSize>0){
            totalPageCount++;
        }
        if (pageIndex>totalPageCount){
            pageIndex=totalPageCount;
        }
        List<SysUser> userList = sysUserService.list(pageIndex, pageSize,realName,roleId);
        model.addAttribute("userList",userList);
        model.addAttribute("realName",realName);
        model.addAttribute("roleId",roleId);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("currentPageNo",pageIndex);
        return "sysUser/list";
    }

    //跳转到添加用户页面
    @RequestMapping("toAdd")
    public String toAdd(){
        return "sysUser/add";
    }

    @RequestMapping("/add")
    public String add(SysUser sysUser,HttpSession session){

        int result=sysUserService.add(sysUser);
        if (result>0){
            return "redirect:/user/list";
        }
        return "sysUser/add";
    }


    @RequestMapping("/del")
    public String del(Integer id){
        sysUserService.delete(id);
        return "redirect:/user/list";
    }


//    @RequestMapping("/view/{id}")
//    public String view(@PathVariable String id,Model model){
//        logger.debug("根据id查询用户详情"+id);
//        SysUser sysUser = sysUserService.getUserById(id);
//        model.addAttribute(sysUser);
//        return "sysUser/view";
//    }

    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam String id,Model model){
        logger.debug("跳转到修改页面");
        SysUser sysUser = sysUserService.getUserById(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }

    @RequestMapping("/update")
    public String update(SysUser sysUser,HttpSession session){
        logger.debug("修改用户信息");
        int result = sysUserService.update(sysUser);

        if (result>0){
            return "redirect:/user/list";
        }

        return "sysUser/update";
    }


//    第十二章示例1
    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account){
        logger.debug("验证用户名account="+account+"的用户是否存在");
        HashMap<String,Object> resultMap = new HashMap<String,Object>();
        if (StringUtils.isNullOrEmpty(account)){
            resultMap.put("exist",1);
        }else {
            SysUser sysUser = sysUserService.getAccountExist(account);
            if (null !=sysUser){
                resultMap.put("exist",1);
            }else {
                resultMap.put("exist",0);
            }
        }
        return JSON.toJSONString(resultMap);
    }


    @ResponseBody
    @GetMapping(value = "/{id}/view")
    public Object view(@PathVariable String id){
        logger.debug("根据id查询用户详情id"+id);
        SysUser sysUser=null;
        try{
            sysUser=sysUserService.getUserById(id);
            logger.debug("查询到用户信息："+sysUser);
        }catch (Exception e){
            e.printStackTrace();
            return "failed";
        }
        return sysUser;
    }
    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "login";
    }

    //跳转到首页
    @RequestMapping("/sys/toMain")
    public String toMain(){
        return "frame";
    }

}
